#!/bin/sh

secret_yaml='/etc/zigbee2mqtt/secret.yaml'

if ! [ -e "$secret_yaml" ]; then
	echo "* Generating $secret_yaml with random values" >&2

	mqtt_password=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 12)
	# The JS code is based on generateNetworkKey() and generatePanId() in lib/zigbee.ts.
	network_key=$(node -e 'console.log(Array.from({length: 16}, () => Math.floor(Math.random() * 255)).join(", "))')
	pan_id=$(node -e 'console.log((Math.floor(Math.random() * (0xFFFF - 2)) + 1).toString(16))')

	install -m640 -o zigbee2mqtt -g zigbee2mqtt /dev/stdin "$secret_yaml" <<-EOF
		# This file has been populated with random values by the zigbee2mqtt
		# post-install script.
		mqtt_password: $mqtt_password
		network_key: [ $network_key ]
		pan_id: 0x$pan_id
	EOF
fi

exit 0
